import type { ApiError } from "@/api/types";
import axios from "axios";

export function normalizeError(err: any): ApiError {
  if (axios.isCancel(err) || err?.name === "CanceledError") {
    return { message: "Request canceled", isCancel: true, raw: err };
  }

  if (!err?.response) {
    // 网络层错误（超时、断网、CORS）
    return {
      message: err?.message || "Network Error",
      isNetworkError: true,
      raw: err,
    };
  }

  const { status, data } = err.response;
  const message =
    (data && (data.message || data.msg)) || err.message || "Request failed";
  return {
    message,
    status,
    code: data?.code,
    raw: err,
  };
}
